<?php

namespace PKApp\Poster;

use PKApp\Poster\Classes\TraitPoster;
use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\Date;
use PKFrame\DataHandler\MatchHelper;
use PKFrame\DataHandler\Numbers;

class AdminSetText extends AdminController
{

    use TraitPoster;

    public function Main()
    {
        $this->callOfSellFunc();
    }

    protected function model(): array
    {
        switch (request()->action()) {
            case 'ApiByCreate':
            case 'ApiByChange':
                $post = $this->checkModel(['posterId', 'text', 'fontColor', 'url', 'timeRange']);
                $post['posterId'] = $this->checkPostFieldIsEmpty('posterId', 'posterIdEmpty');
                Numbers::IsId($post['posterId']) ?: $this->noticeByJson('posterIdEmpty');
                $post['text'] = $this->checkPostFieldIsEmpty('text', 'text_Empty');
                $post['url'] = $this->checkPostFieldIsEmpty('url', 'url_Empty');
                if (!empty($post['fontColor'])) {
                    MatchHelper::MatchFormat('color', $post['fontColor'], 'text_fontColorFormat_Error');
                }
                $post['timeRange'] = $this->checkPostFieldIsEmpty('timeRange', 'timeRange_Empty');
                $timeRange = Date::TimeRangeToArray($post['timeRange']);
                unset($post['timeRange']);
                return array_merge($post, $timeRange);
            case 'ApiByDel':
                return $this->checkModel(['id', 'posterId']);
            case 'ApiBySortIndex':
                return $this->checkModel(['id', 'sortIndex']);
        }
        return [];
    }

    protected function apiByCreate()
    {
        $post = $this->model();
        $model = [
            'siteId' => $this->loginUser()->SiteId,
            'createTime' => time(),
            'listsort' => 0
        ];
        $this->servicePosterOfText()->Add(array_merge($post, $model));
        $this->_inputSuccess();
    }

    public function ApiByChange()
    {
        $post = $this->model();
        $this->servicePosterOfText()->UpdateById(
            $this->checkPostFieldIsEmpty('id', 'posterContent_IdEmpty'),
            $post
        );
        $this->_inputSuccess();
    }

    public function ApiByDel()
    {
        $post = $this->model();
        $this->servicePosterOfText()->DeleteById(
            $this->checkPostFieldIsEmpty('id', 'posterContent_IdEmpty')
        );
        $this->_inputSuccess();
    }

    private function _inputSuccess()
    {
        cache()->Tmp()->RemoveDir(dict('cache_dir'));
        $this->inputSuccess();
    }

    public function ApiBySortIndex()
    {
        $post = $this->model();
        $this->servicePosterOfText()->UpdateById(
            $this->checkPostFieldIsEmpty('id', 'posterIdEmpty'),
            ['listSort' => Numbers::To($post['sortIndex'])]
        );
        $this->inputSuccess();
    }
}